#include "cameraservice.h"
#include <QDebug>
#include <TaskManager.h>

CameraService::CameraService(ImageWindow* imageWindow, QObject* parent)
    : QObject(parent)
    , m_cameraManager(MeCameraManager::getInstance())
    , m_imageWindow(imageWindow)
    , m_hasCurrentFrame(false)
{
    m_autoConnectTimer = new QTimer(this);
    m_autoConnectTimer->setSingleShot(true);
    connect(m_autoConnectTimer, &QTimer::timeout, this, &CameraService::onAutoConnectTimeout);

    setupConnections();
    initialize();
}

CameraService::~CameraService()
{
    disconnectCamera();
}

void CameraService::initialize()
{
    m_cameraManager->initialize();
    log("相机服务初始化完成");

    // 启动时自动尝试连接相机（延迟1秒，确保界面初始化完成）
    m_autoConnectTimer->start(1000);
}

void CameraService::setupConnections()
{
    // 连接相机管理器信号
    connect(m_cameraManager, &MeCameraManager::cameraOpened,
            this, &CameraService::onCameraOpened);
    connect(m_cameraManager, &MeCameraManager::cameraClosed,
            this, &CameraService::onCameraClosed);
    connect(m_cameraManager, &MeCameraManager::frameAcquired,
            this, &CameraService::onFrameAcquired);
    connect(m_cameraManager, &MeCameraManager::errorOccurred,
            this, &CameraService::onErrorOccurred);
    connect(m_cameraManager, &MeCameraManager::devicesEnumerated,
            this, &CameraService::onDevicesEnumerated);
}

void CameraService::onAutoConnectTimeout()
{
    log("正在自动搜索并连接相机...");
    autoConnectToFirstCamera();
}

void CameraService::connectCamera(const QString& ipAddress)
{
    if (ipAddress.isEmpty()) {
        // 如果没有指定IP，自动搜索并连接
        autoConnectToFirstCamera();
    } else {
        log(QString("正在连接相机: %1").arg(ipAddress));
        m_cameraManager->connectCamera(ipAddress);
    }
}

void CameraService::disconnectCamera()
{
    m_cameraManager->disconnectCamera();
    m_hasCurrentFrame = false;
}

void CameraService::triggerSingleShot()
{
    if (isCameraConnected()) {
        m_cameraManager->triggerSingleShot();
        log("单帧采集图像");
    } else {
        log("相机未连接，无法采集");
        emit errorOccurred("相机未连接");
    }
}

void CameraService::enumerateDevices()
{
    m_cameraManager->enumerateDevices();
}

bool CameraService::isCameraConnected() const
{
    return m_cameraManager->isCameraConnected();
}

QString CameraService::getCameraStatus() const
{
    return m_cameraManager->getCameraStatus();
}

void CameraService::autoConnectToFirstCamera()
{
    connect(m_cameraManager, &MeCameraManager::devicesEnumerated,
            this, &CameraService::onDevicesEnumeratedForConnect, Qt::UniqueConnection);
    m_cameraManager->enumerateDevices();
}

void CameraService::onCameraOpened(bool success, const QString& message)
{
    if (success) {
        log("相机连接成功");
        emit cameraOpened(true, message);
    } else {
        log(QString("相机连接失败: %1").arg(message));
        log("请检查：\n1. 相机IP地址是否正确\n2. 网络连接是否正常\n3. 相机是否被其他程序占用");
        emit cameraOpened(false, message);
    }
}

void CameraService::onCameraClosed()
{
    m_hasCurrentFrame = false;
    log("相机已断开");
    emit cameraClosed();
}

void CameraService::onFrameAcquired(const s_Image3dS& frame)
{
    log("✅ 图像采集成功");
    displayFrame(frame);
    TaskManager::instance().completeTaskStatus(TaskType::MANUAL_SINGLE_FRAME_CAPTURE,true,"单帧采集完成");
    emit frameAcquired(frame);

}

void CameraService::onErrorOccurred(const QString& errorMessage)
{
    log("错误: " + errorMessage);
    emit errorOccurred(errorMessage);
}

void CameraService::onDevicesEnumerated(const s_DevicesInfo& devicesInfo)
{
    log(QString("发现 %1 个相机设备").arg(devicesInfo.iNum));

    for (int i = 0; i < devicesInfo.iNum; i++) {
        log(QString("相机 %1: SN=%2, IP=%3, 型号=%4")
                .arg(i + 1)
                .arg(QString::fromStdString(devicesInfo.sCameraInfo[i].SN))
                .arg(QString::fromStdString(devicesInfo.sCameraInfo[i].IpAddr))
                .arg(QString::fromStdString(devicesInfo.sCameraInfo[i].sModelName)));
    }
    emit devicesEnumerated(devicesInfo);
}

void CameraService::onDevicesEnumeratedForConnect(const s_DevicesInfo& devicesInfo)
{
    // 断开这个一次性连接
    disconnect(m_cameraManager, &MeCameraManager::devicesEnumerated,
               this, &CameraService::onDevicesEnumeratedForConnect);

    if (devicesInfo.iNum > 0) {
        // 连接第一个找到的设备
        QString ip = QString::fromStdString(devicesInfo.sCameraInfo[0].IpAddr);
        QString model = QString::fromStdString(devicesInfo.sCameraInfo[0].sModelName);
        QString sn = QString::fromStdString(devicesInfo.sCameraInfo[0].SN);

        m_lastCameraIp = ip;
        log(QString("找到设备: %1 (IP: %2, SN: %3)，正在连接...").arg(model).arg(ip).arg(sn));
        m_cameraManager->connectCamera(ip);
    } else {
        log("未找到可用的相机设备");
        emit errorOccurred("未找到可用的相机设备");
    }
}

void CameraService::displayFrame(const s_Image3dS& frame)
{
    m_currentFrame = frame;
    m_hasCurrentFrame = true;

    // 显示采集的图像
    m_imageWindow->ClearWindow();
    m_imageWindow->DispImage(m_currentFrame.Gray);

    // 显示图像信息
    try {
        HTuple width, height;
        if (m_currentFrame.Gray.IsInitialized()) {
            GetImageSize(m_currentFrame.Gray, &width, &height);
            log(QString("采集图像尺寸: %1 x %2").arg(width.I()).arg(height.I()));
        }
    } catch (...) {
        log("图像尺寸信息获取失败");
    }

    log("图像已加载，可进行后续处理");
}

void CameraService::log(const QString& message)
{
    qDebug() << "[CameraService]" << message;
    emit logMessage(message);
}
